﻿using System;
using System.Linq;
using Medianamik.Client.DAL;
using Medianamik.Client.MVP.Model.DataAccess;

namespace Medianamik.Client.MVP.Model.Service
{
    public class WebUtils : NodeUtils, IWebUtils
    {
        private readonly IMedianamikRepository<IWebPage> _repository;
        public WebUtils(IMedianamikRepository<IBaseType> baseTypeRepository, IMedianamikRepository<IWebPage> webPageRepository)
            : base(baseTypeRepository)
        {
            _repository = webPageRepository;
        }

        public string FirstChildUrl(Guid nodeId)
        {
            string url = "#";
            var pages = _repository.ChildsOf(nodeId, false, -1);

            foreach (IWebPage page in pages)
            {
                url = GetUrl(page);
                break;
            }
            return url;
        }
        public string GetUrl(Guid nodeId)
        {
            IWebPage page = _repository.Get(nodeId);
            return GetUrl(page);
        }
        public string GetUrl(IWebPage page)
        {
            string url = "#";
            return GetUrl(page, url);
        }
        public string GetUrl(IWebPage page, string defaultUrl)
        {
            string url = defaultUrl;

            if (page != null && page.DefaultUrl != null)
            {
                if(page.DefaultUrl.IsAbsoluteUri)
                    url = page.DefaultUrl.AbsolutePath;
                else
                    url = page.DefaultUrl.ToString();
            }
            return url;
        }
        public string GetExternalUrl(string url)
        {
            string path;
            const string http = "http://";

            if (url.IndexOf(http) == -1)
                path = http + url;
            else
                path = url;

            return path;
        }
    }
}